package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.security.auth.login.LoginException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    // 微信服务接口地址
    private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
    //注入配置类 得到Appid和Secret
    @Autowired
    private WeChatProperties weChatProperties;
    //注入用户mapper
    @Autowired
    private UserMapper userMapper;

    /**
     * 微信登陆
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //调用微信接口服务，获取openid
        String openid = getOpenid(userLoginDTO.getCode());
        //openid是否为空。如果为空则表示登录失败
        if (openid == null) {
            //登录失败
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //openid不为空，则判断当前微信用户是否为新用户
        User userByOpenid = userMapper.getByOpenid(openid);
        //如果是新用户，自动完成注册
        if (userByOpenid == null){
            userByOpenid = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(userByOpenid);
        }
        //返回用户对象
        return userByOpenid;
    }

    /**
     * 调用微信接口服务，获取openid
     * @param code
     * @return
     */
    private String getOpenid(String code) {
        //调用微信接口服务，获取当前微信用户的openid
        Map<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());//小程序的appid
        map.put("secret", weChatProperties.getSecret()); //小程序的secret
        map.put("js_code", code); //登录时获取的code
        map.put("grant_type", "authorization_code");//授权类型
        String json = HttpClientUtil.doGet(WX_LOGIN_URL, map);//调用工具类发送请求
        JSONObject jsonObject = JSONObject.parseObject(json);//将json字符串转换为json对象
        String openid = jsonObject.getString("openid"); //openid就是微信用户的唯一标识
        return openid;
     }
}
